package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description 课程计划service接口实现类
 * @date 2022/9/9 11:14
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {
        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if (id != null) {
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        } else {
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count + 1);
            BeanUtils.copyProperties(teachplanDto, teachplanNew);
            teachplanMapper.insert(teachplanNew);
        }
    }

    @Transactional
    @Override
    public void deleteTeachplanById(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan == null) {
            XueChengPlusException.cast("课程计划不存在");
        }
        //获得父节点id
        Long parentid = teachplan.getParentid();
        if (parentid != 0) {
            //删除第二级别的小节的同时需要将其它关联的视频信息也删除
            int i1 = teachplanMapper.deleteById(id);
            if (i1 <= 0) {
                XueChengPlusException.cast("删除课程计划失败");
            }

            //将其它关联的视频信息也删除
            LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TeachplanMedia::getTeachplanId, id);
            int i2 = teachplanMediaMapper.delete(queryWrapper);
//            if(i2 <= 0){
//                XueChengPlusException.cast("删除关联的视频信息失败");
//            }
        } else {
            //删除第一级别的章时要求章下边没有小节方可删除
            Long courseId = teachplan.getCourseId();
            int childCount = getTeachplanCount(courseId, id);
            if (childCount > 0) {
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
            }
            int i = teachplanMapper.deleteById(id);
            if (i <= 0) {
                XueChengPlusException.cast("删除课程计划失败");
            }
        }
    }

    @Transactional
    @Override
    public void deleteTeachplanByCourseId(Long courseId) {
        LambdaQueryWrapper<Teachplan> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Teachplan::getCourseId, courseId);
        teachplanMapper.delete(queryWrapper1);
        LambdaQueryWrapper<TeachplanMedia> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(TeachplanMedia::getCourseId, courseId);
        teachplanMediaMapper.delete(queryWrapper2);
    }

    @Transactional
    @Override
    public void moveUpTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan == null) {
            XueChengPlusException.cast("课程计划不存在");
        }
        //找到在目标课程计划之上的那个课程计划
        Integer orderby = teachplan.getOrderby();
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, teachplan.getCourseId());
        queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());
        queryWrapper.lt(Teachplan::getOrderby, orderby);
        queryWrapper.orderByDesc(Teachplan::getOrderby);
        queryWrapper.last("limit 1");
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        if (teachplans.isEmpty()) {
            XueChengPlusException.cast("已无法上移");
        }
        Teachplan teachplanTemp = teachplans.get(0);
        //交换orderby
        teachplan.setOrderby(teachplanTemp.getOrderby());
        teachplanTemp.setOrderby(orderby);
        int i1 = teachplanMapper.updateById(teachplan);
        int i2 = teachplanMapper.updateById(teachplanTemp);
        if (i1 <= 0 || i2 <= 0) {
            XueChengPlusException.cast("课程计划上移失败");
        }
    }

    @Transactional
    @Override
    public void moveDownTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan == null) {
            XueChengPlusException.cast("课程计划不存在");
        }
        //找到在目标课程计划之下的那个课程计划
        Integer orderby = teachplan.getOrderby();
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, teachplan.getCourseId());
        queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());
        queryWrapper.gt(Teachplan::getOrderby, orderby);
        queryWrapper.orderByAsc(Teachplan::getOrderby);
        queryWrapper.last("limit 1");
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        if (teachplans.isEmpty()) {
            XueChengPlusException.cast("已无法下移");
        }
        Teachplan teachplanTemp = teachplans.get(0);
        //交换orderby
        teachplan.setOrderby(teachplanTemp.getOrderby());
        teachplanTemp.setOrderby(orderby);
        int i1 = teachplanMapper.updateById(teachplan);
        int i2 = teachplanMapper.updateById(teachplanTemp);
        if (i1 <= 0 || i2 <= 0) {
            XueChengPlusException.cast("课程计划下移失败");
        }
    }

    /**
     * @param courseId 课程id
     * @param parentId 父课程计划id
     * @return int 最新排序号
     * @description 获取最新的排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId, long parentId) {
        QueryWrapper<Teachplan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("parentid", parentId);
        queryWrapper.select("IFNULL(max(orderby),0) as orderby");
        Teachplan teachplan = teachplanMapper.selectOne(queryWrapper);
        int count = teachplan.getOrderby();
        return count;
    }

    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null) {
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if (grade != 2) {
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, teachplanId));

        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    @Transactional
    public void deleteAssociationMedia(Long teachPlanId, String mediaId){
        Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
        if (teachplan == null) {
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if (grade != 2) {
            XueChengPlusException.cast("只允许第二级教学计划解除绑定媒资文件");
        }
        //删除该教学计划绑定的媒资
        int delete = teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, teachPlanId).eq(TeachplanMedia::getMediaId, mediaId));
        if (delete <= 0){
            XueChengPlusException.cast("解除该教学计划绑定的媒资失败");
        }
    }
}